//
//  JSListHelper.m
//  JSBasicFramework
//
//  Created by Apple on 2018/8/2.
//  Copyright © 2018年 Apple. All rights reserved.
//

#import "JSListHelper.h"
#import "JSBusiness.h"
#import <MJRefresh/MJRefresh.h>
#import <KafkaRefresh.h>
#import <YYKit.h>
#import <YTKNetwork.h>

@interface JSListHelper ()

@property (nonatomic, assign) ListRefreshStyle refreshStyle;

@property (nonatomic, copy) void(^netWorkResult)(id result, NSInteger currentPage);
@property (nonatomic, copy) void(^netWorkError)(NSError *error);
@property (nonatomic, strong) YTKRequest *request;

@end

@implementation JSListHelper
//- (instancetype)init{
//    if (self = [super init]) {
//    }
//    return self;
//}

-(instancetype)initWithOwner:(id)owner
                     Regiter:(RegisterWithIdentifer) registerBefore
               sectionNumber:(SectionNumber)sectionNumber
                   rowNumber:(RowNumber)rowNumber
               cellIdentifer:(CellIdentifer)cellIdentifer
             headerIdentifer:(HeaderIdentifer)headerIdentifer
             footerIdenrifer:(FooterIdentifer)footerIdentifer
                cellWithSize:(CellWithSize)cellWithSize
              headerWithSize:(HeaderWithSize)headerWithSize
              footerWithSize:(FooterWithSize)footerWithSize
                  cellConfig:(CellConfigData)cellConfig
                headerConfig:(HeaderConfigData)headerConfig
                footerConfig:(FooterConfigData)footerConfig
          didSelectIndexPath:(DidSelectIndexPath)didSelectIndexPath{
    if (self = [super init]) {
        NSAssert(owner, @"Can't be empty");
        NSAssert(cellIdentifer, @"Can't be empty");
        NSAssert(registerBefore, @"Can't be empty");
        
        _refreshStyle = MJ_RefreshStyle;

        self.registerBefore = registerBefore;
        self.cellIdentifer = cellIdentifer;
        self.headerIdentifer = headerIdentifer;
        self.footerIdentifer = footerIdentifer;
        self.rowNumber = rowNumber;
        self.sectionNumber = sectionNumber;
        self.cellWithSize = cellWithSize;
        self.headerWithSize  = headerWithSize;
        self.footerWithSize  = footerWithSize;
        self.didSelectIndexPath = didSelectIndexPath;
        self.cellConfig = cellConfig;
        self.headerConfig = headerConfig;
        self.footerConfig = footerConfig;
        self.owner = owner;
        if ([owner isKindOfClass:[UITableView class]]) {
            UITableView *temp = self.owner;
            temp.dataSource = self;
            temp.delegate   = self;
            temp.tableFooterView = [UIView new];
        }
        if ([owner isKindOfClass:[UICollectionView class]]) {
            UICollectionView *temp = self.owner;
            temp.dataSource = self;
            temp.delegate   = self;
        }
        self.registerBefore(self.owner);
    }
    return self;
}
#pragma mark - UITableViewDelegate and UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.cellIdentifer && self.rowNumber) {
        return self.rowNumber(tableView,section);
    }
    return 0;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.sectionNumber) {
      return self.sectionNumber(tableView);
    }
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.cellWithSize) {
        CGSize size = self.cellWithSize(tableView,indexPath);
        return size.height;
    }
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.headerIdentifer && self.headerIdentifer && self.headerWithSize) {
        return self.headerWithSize(tableView,section).height;
    }
    return 0;
}
- (NSArray <NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    if (self.indexTitlesForTableView) {
        return self.indexTitlesForTableView(tableView);
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (self.footerIdentifer && self.footerWithSize) {
        return self.footerWithSize(tableView,section).height;
    }
    return 0;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *identifer = self.cellIdentifer(tableView, indexPath);
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
    if (self.cellConfig) {
        self.cellConfig(cell, indexPath);
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.didSelectIndexPath) {
        self.didSelectIndexPath(tableView, indexPath);
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (self.footerIdentifer) {
        UITableViewHeaderFooterView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:self.footerIdentifer(tableView,section)];
        if (self.footerConfig) {
            self.footerConfig(view, section);
        }
        return view;
    }
    return nil;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (self.headerIdentifer) {
        UITableViewHeaderFooterView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:self.headerIdentifer(tableView,section)];
        if (self.headerConfig) {
            self.headerConfig(view, section);
        }
        return view;
    }
    return nil;
}
#pragma mark - UICollectionViewDelegate and UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.rowNumber) {
        return self.rowNumber(collectionView,section);
    }
    return 0;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if (self.sectionNumber) {
        return self.sectionNumber(collectionView);
    }
    return 1;
}

//MARK:设置每个item的大小，
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.cellWithSize) {
        return self.cellWithSize(collectionView,indexPath);
    }
    return CGSizeZero;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:self.cellIdentifer(collectionView,indexPath) forIndexPath:indexPath];
//    if ([JSBusiness sharedInstance].isDebug) {
//         cell.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];
//    }
    if (self.cellConfig) {
        self.cellConfig(cell, indexPath);
    }
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.didSelectIndexPath) {
        self.didSelectIndexPath(collectionView, indexPath);
    }
}
//动态设置某个分区头视图大小

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (self.headerIdentifer && self.headerWithSize) {
        return self.headerWithSize(collectionView, section);
    }
    return CGSizeZero;
}
//动态设置某个分区尾视图大小

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if (self.footerIdentifer && self.footerWithSize) {
        return self.footerWithSize(collectionView, section);
    }
    return CGSizeZero;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:self.headerIdentifer(collectionView, indexPath.section) forIndexPath:indexPath];
        if (self.headerConfig) {
            self.headerConfig(view, indexPath.section);
        }
        return view;
    }else if ([kind isEqualToString:UICollectionElementKindSectionFooter]){
        NSString *identifer = self.footerIdentifer(collectionView, indexPath.section);
        if (identifer) {
            UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:identifer forIndexPath:indexPath];
            if (self.footerConfig) {
                self.footerConfig(view, indexPath.section);
            }
            return view;
        }
       
    }
    return nil;
}

// 添加刷新
- (void)setHeaderRefresh:(ListViewRefresh)headerRefresh{
    _headerRefresh = headerRefresh;
    UIScrollView *scorll = self.owner;
    if (self.refreshStyle == MJ_RefreshStyle) {
        if (_headerRefresh) {
            
            scorll.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefreshAct)];
            scorll.mj_header.automaticallyChangeAlpha = YES;
            
        }else{
            scorll.mj_header = nil;
        }

    }else if (self.refreshStyle == Kaka_RefreshStyle){
        
        if (headerRefresh) {
            @weakify(self)
            [scorll bindHeadRefreshHandler:^{
                
                @strongify(self)
                [self headerRefreshAct];
                
            } themeColor:[UIColor blueColor] refreshStyle:KafkaRefreshStyleReplicatorCircle];
        }else{
            scorll.headRefreshControl = nil;
        }
    }

}
- (void)setFooterRefresh:(ListViewRefresh)footerRefresh{
    _footerRefresh = footerRefresh;
    UIScrollView *scorll = self.owner;

    if (self.refreshStyle == MJ_RefreshStyle) {
        if (_footerRefresh) {
            scorll.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefreshAct)];
            scorll.mj_footer.automaticallyChangeAlpha = YES;
            [scorll.mj_footer endRefreshingWithNoMoreData];
        }else{
            scorll.mj_footer = nil;
        }

    }else if (self.refreshStyle == Kaka_RefreshStyle){
        if (footerRefresh) {
            @weakify(self)
            [scorll bindFootRefreshHandler:^{
                
                @strongify(self)
                [self footerRefreshAct];
                
            } themeColor:[UIColor blueColor] refreshStyle:KafkaRefreshStyleReplicatorCircle];
        }else{
            scorll.footRefreshControl = nil;
        }
    }

   
    
}
-(void)headerRefreshAct{
    if (self.headerRefresh) {
        self.headerRefresh(self, self.owner);
    }
}
-(void)footerRefreshAct{
    if (self.footerRefresh) {
        self.footerRefresh(self, self.owner);
    }
}


// 1. 手动触发刷新
- (void)beginRefreshing:(ListRefrehState)refreshState{
    UIScrollView *scroll = self.owner;
    if (self.refreshStyle == MJ_RefreshStyle) {
        if (refreshState == ListRefreshStateHeader) {
            [scroll.mj_header beginRefreshing];
        }else if (refreshState == ListRefreshStateFooter){
            [scroll.mj_footer beginRefreshing];
        }
    }else if (self.refreshStyle == Kaka_RefreshStyle){
        if (refreshState == ListRefreshStateHeader) {
            [scroll.headRefreshControl beginRefreshing];
        }else if (refreshState == ListRefreshStateFooter){
            [scroll.footRefreshControl beginRefreshing];
        }
    }
}
/*
 一般方式结束刷新
 */
- (void)endRefreshing:(ListRefrehState)refreshState{
    
    UIScrollView *scroll = self.owner;
    if (self.refreshStyle == MJ_RefreshStyle) {
        if (refreshState == ListRefreshStateAll) {
            [scroll.mj_header endRefreshing];
            [scroll.mj_footer endRefreshing];
        }else if (refreshState == ListRefreshStateHeader){
            [scroll.mj_header endRefreshing];
            
        }else if (refreshState == ListRefreshStateFooter){
            [scroll.mj_footer endRefreshing];
        }
        
    }else if (self.refreshStyle == Kaka_RefreshStyle){
        if (refreshState == ListRefreshStateAll) {
            [scroll.headRefreshControl endRefreshing];
            [scroll.footRefreshControl endRefreshing];
        }else if (refreshState == ListRefreshStateHeader){
            [scroll.headRefreshControl endRefreshing];
            
        }else if (refreshState == ListRefreshStateFooter){
            [scroll.footRefreshControl endRefreshing];
        }
    }
}

/*
 结束刷新且需要提示文字
 */
- (void)endRefreshingWithRefresh:(ListRefrehState)refreshState alertText:(NSString *)text completion:(dispatch_block_t)completion{
    
    UIScrollView *scroll = self.owner;
    if (self.refreshStyle == MJ_RefreshStyle) {
        if (refreshState == ListRefreshStateAll) {
            [scroll.mj_header endRefreshing];
            [scroll.mj_footer endRefreshing];
        }else if (refreshState == ListRefreshStateHeader){
            [scroll.mj_header endRefreshing];
            
        }else if (refreshState == ListRefreshStateFooter){
            [scroll.mj_footer endRefreshing];
        }
        
    }else if (self.refreshStyle == Kaka_RefreshStyle){
        if (refreshState == ListRefreshStateAll) {
            [scroll.headRefreshControl endRefreshing];
            [scroll.footRefreshControl endRefreshing];
        }else if (refreshState == ListRefreshStateHeader){
            [scroll.headRefreshControl endRefreshingWithAlertText:text completion:completion];
            
        }else if (refreshState == ListRefreshStateFooter){
            [scroll.footRefreshControl endRefreshingWithAlertText:text completion:completion];
        }
        
    }
}

/*
 结束刷新且不再需要刷新功能
 */
- (void)endRefreshingAndNoLongerRefreshingWithAlertText:(NSString *)text{
    
    UIScrollView *scroll = self.owner;
    if (self.refreshStyle == MJ_RefreshStyle) {
        
        [scroll.mj_footer endRefreshingWithNoMoreData];
    }else if (self.refreshStyle == Kaka_RefreshStyle){
        [scroll.footRefreshControl endRefreshingAndNoLongerRefreshingWithAlertText:text];
    }
}

- (void)resumeRefreshAvailable{
    UIScrollView *scroll = self.owner;
    if (self.refreshStyle == MJ_RefreshStyle) {
        [scroll.mj_footer resetNoMoreData];
    }else if (self.refreshStyle == Kaka_RefreshStyle){
        [scroll.footRefreshControl resumeRefreshAvailable];
    }
}
-(void)reloadData{
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([self.owner isKindOfClass:[UITableView class]]) {
            UITableView *temp = self.owner;
            [temp reloadData];
        }
        if ([self.owner isKindOfClass:[UICollectionView class]]) {
            UICollectionView *temp = self.owner;
            [temp reloadData];
        }
    });
   
}
-(instancetype)initializeEmptyData{
    NSAssert(self, @"Can't be initialize");
    UIScrollView *scorll = self.owner;
    scorll.emptyDataSetSource = self;
    scorll.emptyDataSetDelegate = self;
    return self;
}
- (void)resetEmpatyData{
    UIScrollView *scorll = self.owner;
   scorll.emptyDataSetSource = nil;
   scorll.emptyDataSetDelegate = nil;
}
/*
 设置Empty
 */
-(void) settingEmptyDataTitle:(EmptyDataTitle)title
                    dataImage:(EmptyDataImage)image
                  detailTitle:(EmptyDataDetailTitle)detailTitle
                  buttonTitle:(EmptyDataButtonTitle)buttonTitle
                  buttonImage:(EmptyDataButtonImage)buttonImage
                    backColor:(EmptyDataBackColor)backColor
                       offSet:(EmptyDataVerticalOffSet)offSet
                   customView:(EmptyDataCustomView)customView
                verticalSpace:(EmptyDataVerticalSpace)verticalSpace
                 shouldScroll:(EmptyDataShouldAllScroll)sholdScroll
                    buttonTap:(EmptyDataDidTapButton)buttonTap{
    
    _emptyTitle = title;
    _emptyDetailTitle = detailTitle;
    _emptyButtonTitle = buttonTitle;
    _emptyButtonImage = buttonImage;
    _emptyBackColor = backColor;
    _emptyVerticalOfferSet = offSet;
    _emptyCustomView = customView;
    _emptyVerticatialSpace = verticalSpace;
    _emptyShouldScroll = sholdScroll;
    _emptyButtonTap = buttonTap;
    _emptyImage     = image;

}
- (void)setEmptyTitle:(EmptyDataTitle)emptyTitle{
    _emptyTitle = emptyTitle;
    [self reloadData];
}
- (void)setEmptyDetailTitle:(EmptyDataDetailTitle)emptyDetailTitle{
    _emptyDetailTitle = emptyDetailTitle;
    [self reloadData];
}
- (void)setEmptyButtonTitle:(EmptyDataButtonTitle)emptyButtonTitle{
    _emptyButtonTitle = emptyButtonTitle;
    [self reloadData];
}
- (void)setEmptyButtonImage:(EmptyDataButtonImage)emptyButtonImage{
    _emptyButtonImage = emptyButtonImage;
    [self reloadData];
}
- (void)setEmptyBackColor:(EmptyDataBackColor)emptyBackColor{
    _emptyBackColor = emptyBackColor;
    [self reloadData];
}
- (void)setEmptyVerticalOfferSet:(EmptyDataVerticalOffSet)emptyVerticalOfferSet{
    _emptyVerticalOfferSet = emptyVerticalOfferSet;
    [self reloadData];
}
- (void)setEmptyCustomView:(EmptyDataCustomView)emptyCustomView{
    _emptyCustomView = emptyCustomView;
    [self reloadData];
}
- (void)setEmptyVerticatialSpace:(EmptyDataVerticalSpace)emptyVerticatialSpace{
    _emptyVerticatialSpace = emptyVerticatialSpace;
    [self reloadData];
}
- (void)setEmptyShouldScroll:(EmptyDataShouldAllScroll)emptyShouldScroll{
    _emptyShouldScroll = emptyShouldScroll;
    [self reloadData];
}
- (void)setEmptyButtonTap:(EmptyDataDidTapButton)emptyButtonTap{
    _emptyButtonTap = emptyButtonTap;
    [self reloadData];
}
- (void)setEmptyImage:(EmptyDataImage)emptyImage{
    _emptyImage = emptyImage;
    [self reloadData];
}

#pragma mark - DZNEmptyDataSource -  可以在这里设置默认值

// 标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView{
    if (self.emptyTitle) {
        return self.emptyTitle(scrollView);
    }
    return [[NSAttributedString alloc] initWithString:@"当前无数据" attributes:@{NSFontAttributeName:UIFontMake(KREALVALUE(14)),NSForegroundColorAttributeName:JS_colorWithHex(kLowerGray)}];
}
// 详情文字
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView{
    if (self.emptyDetailTitle) {
        return self.emptyDetailTitle(scrollView);
    }
    return [[NSAttributedString alloc] initWithString:@""];
}
// 文字按钮
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state{
    if (self.emptyButtonTitle) {
        return self.emptyButtonTitle(scrollView, state);
    }
    return [[NSAttributedString alloc] initWithString:@""];
}
// 图片按钮
- (UIImage *)buttonImageForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state{
    if (self.emptyButtonImage) {
        return self.emptyButtonImage(scrollView, state);
    }
    return nil;
}
// 空页面占位图
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    if (self.emptyImage) {
       return self.emptyImage(scrollView);
    }
    return UIImageMake(@"message_placeholder");
}
// 背景颜色
- (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView{
    if (self.emptyBackColor) {
        return self.emptyBackColor(scrollView);
    }
    return [UIColor clearColor];
}
// 垂直偏移量
- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView{
    if (self.emptyVerticalOfferSet) {
        return self.emptyVerticalOfferSet(scrollView);
    }
    return 0;
//    UIImage *image = UIImageMake(@"noData");
//    UIScrollView *temp = self.owner;
//    return -(temp.height - (image.size.width / temp.width) * image.size.height) / 2;
}
// 自定义视图
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView{
    if (self.emptyCustomView) {
        return self.emptyCustomView(scrollView);
    }
    return nil;
}
// 垂直间距
- (CGFloat)spaceHeightForEmptyDataSet:(UIScrollView *)scrollView{
    if (self.emptyVerticatialSpace) {
        return self.emptyVerticatialSpace(scrollView);
    }
    return 0.0;
}
// 是否允许滚动
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    if (self.emptyShouldScroll) {
        return self.emptyShouldScroll(scrollView);
    }
    return YES;
}
// 空白处点击事件
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view{

}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button{
    if (self.emptyButtonTap) {
        self.emptyButtonTap(scrollView);
    }
}

-(void)setRefrenshWithRequest:(YTKRequest *)request
               withCompletion:(void(^)(id result, NSInteger curentPage))completion
                        error:(void(^)(NSError *))faild{
    if (request == nil && faild) {
        faild([NSError errorWithDomain:NSURLErrorDomain code:-1 userInfo:@{NSURLErrorFailingURLErrorKey:@"请求不存在"}]);
        return;
    }
    self.netWorkResult = [completion copy];
    self.netWorkError  = [faild copy];
    self.request       = request;
    [self setHeaderRefresh:^(JSListHelper *helper, id owner) {
        [helper endRefreshing:(ListRefreshStateFooter)];
        [helper loadData:YES];
    }];
    [self setFooterRefresh:^(JSListHelper *helper, id owner) {
        [helper endRefreshing:(ListRefreshStateHeader)];
        [helper loadData:NO];
        
    }];
    
   
}
- (void)loadData:(BOOL )isNew{
    if (self.request.currentPage < 0) {
        if (self.netWorkError) {
            self.netWorkError([NSError errorWithDomain:NSURLErrorDomain code:-1 userInfo:@{@"message":@"请求类未初始化currentPage"}]);
        }
        return;
    }
    if (isNew) {
        self.request.currentPage = 0;
    }else{
        self.request.currentPage += 1;
    }
    @weakify(self)
    [self.request.rac_requestSignal subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        dispatch_async(dispatch_get_main_queue(), ^{
            [self endRefreshing:(ListRefreshStateAll)];
        });
        if (self.netWorkResult) {
            self.netWorkResult(x, self.request.currentPage);
        }
        // 判断当前数量
        NSArray *temp = nil;
        if (ValidDict(x)) {
            temp = x[@"content"];
        }
        if (ValidArray(x)) {
            temp = x;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if (temp.count < self.request.pageSize) {
                [self endRefreshingAndNoLongerRefreshingWithAlertText:@"没有更多数据"];
            }else{
                [self resumeRefreshAvailable];
            }
        });
    } error:^(NSError * _Nullable error) {
        @strongify(self)
        dispatch_async(dispatch_get_main_queue(), ^{
            [self endRefreshing:(ListRefreshStateAll)];
            [self endRefreshingAndNoLongerRefreshingWithAlertText:@"没有更多数据"];
            
        });
        if (self.request.currentPage >= 1) {
            self.request.currentPage -= 1;
        }
        if (self.netWorkError) {
            self.netWorkError(error);
        }
    }];
//    [self.request startWithCompletionBlockWithSuccess:^(__kindof YTKRequest * _Nonnull request) {
//        @strongify(self)
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self endRefreshing:(ListRefreshStateAll)];
//        });
//        if ([request.responseObject[@"code"] integerValue] == 200 || [request.responseObject[@"code"] integerValue] == 204) {
//            if (self.netWorkResult) {
//                self.netWorkResult(request, request.currentPage);
//            }
//        }else{
//            if (self.netWorkError) {
//                self.netWorkError([NSError errorWithDomain:NSURLErrorDomain code:-1 userInfo:@{@"message":request.responseObject[@"message"]}]);
//            }
//            if (isDebug) {
//                [JSProgressHUD agency_showFialdMsg:request.responseObject[@"message"] InView:nil];
//            }
//        }
//
//        // 判断当前数量
//        NSArray *temp = request.responseObject[@"body"][@"dataList"];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if (temp.count < request.pageSize) {
//                [self endRefreshingAndNoLongerRefreshingWithAlertText:@"没有更多数据"];
//            }else{
//                [self resumeRefreshAvailable];
//            }
//        });
//
//    } failure:^(__kindof YTKRequest * _Nonnull request) {
//        @strongify(self)
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self endRefreshing:(ListRefreshStateAll)];
//            [self endRefreshingAndNoLongerRefreshingWithAlertText:@"没有更多数据"];
//
//        });
//        if (self.request.currentPage >= 1) {
//            self.request.currentPage -= 1;
//        }
//        if (self.netWorkError) {
//            self.netWorkError(request.error);
//        }
//    }];
}
@end

@implementation YTKRequest (Page)

- (NSInteger)currentPage{
    NSNumber *curpage = objc_getAssociatedObject(self, _cmd);
    if (curpage.integerValue >= 0) {
        return curpage.integerValue;
    }
    return -1;
}
- (void)setCurrentPage:(NSInteger)currentPage{
    objc_setAssociatedObject(self, @selector(currentPage), @(currentPage), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSInteger)pageSize{
    NSNumber *pagesize = objc_getAssociatedObject(self, _cmd);
    if (pagesize.integerValue > 0) {
        return pagesize.integerValue;
    }
    return 20;
}
- (void)setPageSize:(NSInteger)pageSize{
    objc_setAssociatedObject(self, @selector(pageSize), @(pageSize), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end
